//
//  ClubGameForumDetailView.swift
//  77Club
//
//  Created by Apple on 2024/11/19.
//

import UIKit
import VersaPlayer
import MediaPlayer

//MARK: 动态详情内容cell
class ClubGameForumDetailCell: UITableViewCell {
    
    private let bannarCollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let playerView = VersaPlayerView()
    private var controls = VersaPlayerControls()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(16.font_semiBold).line(0).end()
    private let contentLabel = c_make_ex(UITextView.self)
        .color("#4B4C4D").font(15.font_regular).end()
    private var imgs = [String]()
    private let pageView = c_make_ex(UIView.self)
        .bgColor("#F7F8FA".toColor.alpha(0.3)).corner(11).end()
    private let currenPage = c_make_ex(UILabel.self)
        .color(.white).font(12.font_semiBold).alignment(.right).end()
    private let gameView = c_make_ex(UIView.self)
        .corner(8.0.Scale).bgColor("#4B4C4D").end()
    private let gameImageV = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).corner(8.0.Scale).end()
    private let gameNameLabel = c_make_ex(UILabel.self)
        .color(.white).font(12.font_semiBold).end()
    private var gameSubLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.85)).font(10.font_medium).end()
    private let totalPage = c_make_ex(UILabel.self)
        .color(.white.alpha(0.5)).font(9.font_semiBold).end()
    lazy var slider: VersaSeekbarSlider = {
       let makeView = VersaSeekbarSlider()
        //  最小值
        makeView.minimumValue = 0.0
        //  最大值
        makeView.maximumValue = 100.0
        //  设置默认值
//        makeView.setValue(sliderDefalutValue, animated: true)
        //  滑动条有值部分颜色
        makeView.minimumTrackTintColor = .white
        //  滑动条没有值部分颜色
        makeView.maximumTrackTintColor = .black.alpha(0.5)
        makeView.isUserInteractionEnabled = false
        makeView.setThumbImage(UIImage(), for: .normal)
        return makeView
    }()
    private let playButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_play",state: .selected).image("Dynamic_detail_pause").end()
    private let fullButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_full").end()
    private let voiceButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_aloud").image("Dynamic_detail_slience", state: .selected).end()
    private lazy var timeLabel = c_make_ex(UILabel.self)
        .color(.white).font(10.font_medium).alignment(.right).end()
    private var isFull = false
    
    var popBlock:(()->())?
    /// 点击图片
    var didSelectImage:((_:Int,_:[String])->())?
    
    var model: ClubGameCommunityDetailModel?{
        didSet{
            guard let md = model else { return }
            if md.video.count > 0 {
                bannarCollectionView.isHidden = true
                playerView.isHidden = false
                if let url = URL.init(string: md.video) {
                    let item = VersaPlayerItem(url: url)
                    playerView.set(item: item)
                }
                titleLabel.topConstraint?.constant = 215
                pageView.isHidden = true
            }else if md.image.count > 0{
//                pageView.isHidden = false
                bannarCollectionView.isHidden = false
                playerView.isHidden = true
                totalPage.text = "/\(md.image.count)"
                currenPage.text = "1"
                self.imgs = md.image
                bannarCollectionView.reloadData()
                titleLabel.topConstraint?.constant = 215
            }else{
                pageView.isHidden = true
                bannarCollectionView.isHidden = true
                playerView.isHidden = true
                titleLabel.topConstraint?.constant = 5
            }
            titleLabel.text = md.title
//            contentLabel.text = md.content
            // 将 Base64 字符串解码为 Data
            guard let decodedData = Data(base64Encoded: md.content)else { return }
            // 将 Data 转换为字符串
            let decodedString = String(data: decodedData, encoding: .utf8) ?? ""
//            self.loadHTML(htmlString: decodedString ?? "")
            let data = Data(decodedString.utf8)
            let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
            ]

            do {
                let attributedString = try NSAttributedString(data: data, options: options, documentAttributes: nil)
                let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString)
                let fullRange = NSRange(location: 0, length: mutableAttributedString.length)
                mutableAttributedString.addAttribute(.font, value: 14.font_regular!, range: fullRange)
                mutableAttributedString.addAttribute(.foregroundColor, value: "#4B4C4D".toColor, range: fullRange)
                contentLabel.attributedText = mutableAttributedString
            } catch {
                print("Failed to parse HTML: \(error)")
            }
//            contentLabel.text = decodedString
            
            let size = CGSize(width: CGFloat.screenWidth - 104.0.Scale, height: .greatestFiniteMagnitude)
            let optionsa: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
                // 使用 boundingRect 方法计算高度
            let boundingRect = contentLabel.attributedText.boundingRect(with: size, options: optionsa, context: nil)
            self.contentLabel.heightConstraint?.constant = ceil(boundingRect.height)
        }
    }
    
    var gameModel: ClubGameDetailModel?{
        didSet{
            guard let md = gameModel else { return }
            gameImageV.loadImage(url: md.icon)
            gameNameLabel.text = md.name
            let tagStr = md.biaoqian.joined(separator: " · ")
            let subStr = String(md.point) + " · " + tagStr
            gameSubLabel.text = subStr
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            bannarCollectionView
            playerView
            titleLabel
            contentLabel
            pageView.subviews{
                currenPage
                totalPage
            }
            gameView.subviews{
                gameImageV
                gameNameLabel
                gameSubLabel
            }
        }
        
        playerView.use(controls: controls)
        
        let bannarLayout = UICollectionViewFlowLayout()
        bannarLayout.minimumLineSpacing = 0
        bannarLayout.minimumInteritemSpacing = 0
        bannarLayout.scrollDirection = .horizontal
        bannarLayout.itemSize = CGSize(width: .screenWidth, height: 210)
        
        bannarCollectionView.collectionViewLayout = bannarLayout
        bannarCollectionView.backgroundColor = .clear
        bannarCollectionView.register(ClubDynamicDetailBannarCell.self, forCellWithReuseIdentifier: ClubDynamicDetailBannarCell.description())
        bannarCollectionView.showsHorizontalScrollIndicator = false
        bannarCollectionView.delegate = self
        bannarCollectionView.dataSource = self
        bannarCollectionView.isPagingEnabled = true
        
        bannarCollectionView.leading(0).top(0).height(210).width(.screenWidth)
        playerView.leading(0).top(0).height(210).width(.screenWidth)
        titleLabel.leading(12).trailing(12).top(215)
        contentLabel.leading(12).trailing(12)
        contentLabel.Top == titleLabel.Bottom + 12.0.Scale
        gameView.leading(12.0.Scale).trailing(12.0.Scale).height(56.0.Scale).bottom(16.0.Scale)
        gameView.Top == contentLabel.Bottom + 16.0.Scale
        gameImageV.leading(12.0.Scale).size(32.0.Scale).centerVertically()
        gameNameLabel.top(11.0.Scale).leading(56.0.Scale)
        gameSubLabel.leading(56.0.Scale).trailing(12.0.Scale).height(16).top(28.0.Scale)
        pageView.width(45).height(22).centerHorizontally()
        pageView.Bottom == bannarCollectionView.Bottom - 12
        totalPage.leading(22.5).centerVertically()
        currenPage.trailing(22.5).centerVertically()
        
        contentLabel.isEditable = false
        contentLabel.isScrollEnabled = false
        contentLabel.isUserInteractionEnabled = true
        contentLabel.backgroundColor = .clear
        contentLabel.translatesAutoresizingMaskIntoConstraints = false
        contentLabel.textContainerInset = .zero
        contentLabel.textContainer.lineFragmentPadding = 0
        
        playerView.backgroundColor = .black
        playerView.playbackDelegate = self
        playerView.controls?.behaviour.showingControls = true
        playerView.isHidden = true
        
        controls.subviews{
            slider
            playButton
            fullButton
            voiceButton
            timeLabel
        }
        
        playButton.leading(0).bottom(0).size(44)
        slider.leading(48).height(1.5).width(205)
        slider.CenterY == playButton.CenterY
        fullButton.trailing(12).size(24)
        fullButton.CenterY == playButton.CenterY
        voiceButton.trailing(36).size(24)
        voiceButton.CenterY == playButton.CenterY
        timeLabel.trailing(60)
        timeLabel.CenterY == playButton.CenterY
        
        playButton.addTarget(self, action: #selector(clickPlayButton), for: .touchUpInside)
        voiceButton.addTarget(self, action: #selector(clickVoiceButton), for: .touchUpInside)
        fullButton.addTarget(self, action: #selector(clickFullButton), for: .touchUpInside)
        
        NotificationCenter.default.addObserver(self, selector: #selector(stopVideoPlay), name: .stopDetailAudioPlayer, object: nil)
        
        let gameTap = UITapGestureRecognizer(target: self, action: #selector(clickGameView))
        gameView.isUserInteractionEnabled = true
        gameView.addGestureRecognizer(gameTap)
    }
    
    @objc private func clickGameView(){
        popBlock?()
    }
    
    @objc private func stopVideoPlay(){
        playerView.pause()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//MARK: action
extension ClubGameForumDetailCell: VersaPlayerPlaybackDelegate {
    
    @objc private func clickPlayButton(){
        self.playButton.isSelected = !self.playButton.isSelected
        if self.playButton.isSelected {
            playerView.pause()
        }else{
            playerView.play()
        }
    }
    
    @objc private func clickFullButton(){
        
        self.isFull = !self.isFull
        self.playerView.setFullscreen(enabled: self.isFull)
    }
    
    @objc private func clickVoiceButton(){
        self.voiceButton.isSelected = !self.voiceButton.isSelected
        if self.voiceButton.isSelected {
            playerView.player.volume = 0
        }else{
            playerView.player.volume = 1
        }
    }
    
    func timeDidChange(player: VersaPlayer, to time: CMTime) {
        
        let seconds = CMTimeGetSeconds(time)
        let endTime = CMTimeGetSeconds(player.endTime())
        
        let currentT = CMTimeGetSeconds(time)
        let currentTStr = Int(currentT).toPlayTimeStr()
        let endTStr = Int(endTime).toPlayTimeStr()
        timeLabel.text = currentTStr + "/" + endTStr
        let totalT = self.playerView.player.endTime().seconds
        let progress = currentT / totalT * 100.0
        slider.value = Float(progress)
        
        if Int(seconds) == Int(endTime) {
            player.pause()
            let time:CMTime = CMTimeMakeWithSeconds(0.1, preferredTimescale: 1 * Int32(NSEC_PER_SEC))
            player.seek(to: time, toleranceBefore: CMTime.zero, toleranceAfter:CMTime.zero)
            player.play()
        }
        
    }
}

//MARK: action
extension ClubGameForumDetailCell: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubDynamicDetailBannarCell.description(), for: indexPath) as? ClubDynamicDetailBannarCell else { return UICollectionViewCell() }
        cell.imgUrl = imgs[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if model?.image.count ?? 0 > 0 {
            didSelectImage?(indexPath.row,model?.image ?? [])
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let collectionView = scrollView as? UICollectionView else { return }

        guard let collectionView = scrollView as? UICollectionView else { return }
            
            let visibleCells = collectionView.visibleCells
            for cell in visibleCells {
                // 获取 cell 在 CollectionView 中的位置
                if let indexPath = collectionView.indexPath(for: cell) {
                    // 判断该 cell 是否完全可见
                    let cellFrame = collectionView.layoutAttributesForItem(at: indexPath)?.frame ?? .zero
                    let cellVisibleRect = collectionView.bounds.intersection(cellFrame)

                    if cellVisibleRect == cellFrame {
                        self.currenPage.text = "\(indexPath.row + 1)"
                    }
                }
            }
    }
}


//MARK:写点什么cell
//class ClubGameForumDetailSayCell: UITableViewCell {
//    
//    private let bgView = c_make_ex(UIView.self)
//        .bgColor(.white).corner(12).end()
//    private let iconImageView = c_make_ex(UIImageView.self)
//        .mode(.scaleAspectFill).corner(20).end()
//    private let titleLabel = c_make_ex(UILabel.self)
//        .color("#7D7E80").font(11.font_medium).bgColor("#7B7D80".toColor.alpha(0.08))
//        .corner(15).text("  写点什么...").end()
//    
//    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
//        
//        super.init(style: style, reuseIdentifier: reuseIdentifier)
//        selectionStyle = .none
//        backgroundColor = .clear
//        contentView.backgroundColor = .clear
//        
//        contentView.subviews{
//            bgView.subviews{
//                iconImageView
//                titleLabel
//            }
//        }
//        
//        bgView.leading(12.0.Scale).trailing(12.0.Scale).height(72.0.Scale).bottom(12.0.Scale).top(0)
//        iconImageView.leading(16.0.Scale).size(40).centerVertically()
//        titleLabel.leading(68.0.Scale).trailing(16.0.Scale).height(30).centerVertically()
//
//        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
//            iconImageView.loadImage(url: ClubUser.face)
//        }else{
//            iconImageView.image = "Common_defaultIcon".toImage
//        }
//        
//    }
//
//    required init?(coder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//}
